package com.star.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.system.entity.UserRole;
import com.star.system.mapper.UserRoleMapper;
import com.star.system.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色用户 服务实现类
 *
 * @author yangzj
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatch(Long userId, List<Long> roleIds) {
        this.saveBatch(roleIds.stream().map(c -> new UserRole()
                .setUserId(userId)
                .setRoleId(c))
                .collect(Collectors.toList()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBatch(Long userId, List<Long> roleIds) {
        this.deleteByUserIds(Collections.singletonList(userId));
        if(CollUtil.isNotEmpty(roleIds)){
            this.saveBatch(userId, roleIds);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByRoleIds(List<Long> roleIds) {
        this.lambdaUpdate().in(UserRole::getRoleId, roleIds).remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByUserIds(List<Long> userIds) {
        this.lambdaUpdate().in(UserRole::getUserId, userIds).remove();
    }
}
